<template>
  <div class="qrcode-tool">
    <h2>二维码生成</h2>
    <input v-model="text" type="text" placeholder="输入内容" />
    <button @click="generateQRCode">生成二维码</button>
    <div class="qrcode-result" v-if="generated">
      <canvas ref="qrcodeCanvas"></canvas>
    </div>
    <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
  </div>
</template>

<script>
import QRCode from 'qrcode';

export default {
  name: 'QRCodeTool',
  data() {
    return {
      text: '',
      generated: false,
      errorMessage: '',
    };
  },
  methods: {
    generateQRCode() {
      if (!this.text) {
        this.errorMessage = '请输入内容';
        return;
      }
      this.errorMessage = '';
      // 使用 qrcode 库生成二维码到 canvas 中
      QRCode.toCanvas(this.$refs.qrcodeCanvas, this.text, { width: 200 }, (error) => {
        if (error) {
          this.errorMessage = '生成二维码失败';
          console.error(error);
          this.generated = false;
        } else {
          this.generated = true;
        }
      });
    },
  },
};
</script>

<style scoped>
.qrcode-tool {
  max-width: 600px;
  margin: 0 auto;
  text-align: center;
}
input {
  width: calc(100% - 22px);
  padding: 10px;
  margin: 10px 0;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  transition: border-color 0.3s;
}
input:focus {
  border-color: #3498db;
}
button {
  padding: 10px 20px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
button:hover {
  background-color: #2980b9;
}
.qrcode-result {
  margin-top: 20px;
}
.error {
  color: red;
  margin-top: 10px;
}
</style> 